#!/usr/bin/env bash
# Usage: List all Swift versions available to swiftenv

set -e

unset bare
unset verbose
for arg; do
  case "$arg" in
  --bare ) bare=1 ;;
  --verbose ) verbose=1 ;;
  esac
done

CURRENT_VERSION=$(swiftenv-version-name || true)

printed=" "
print_version() {
  # Don't print if we've already printed it
  if [[ "$printed" != *" $1 "* ]]; then
    local version
    version="${1##swift-}"
    if [ -n "$bare" ]; then
      echo "$version"
    elif [ "$version" == "$CURRENT_VERSION" ]; then
      if [ -n "$verbose" ]; then
      echo "* $version [from $2] (set by $(swiftenv-version-origin))"
      else
      echo "* $version (set by $(swiftenv-version-origin))"
      fi
    elif [ -n "$verbose" ]; then
      echo "  $version [from $2]"
    else
      echo "  $version"
    fi

    printed="$printed$1 "
  fi
}

VERSIONS_DIR="$SWIFTENV_ROOT/versions"

if [ "$CURRENT_VERSION" == "system" ]; then
  echo "* system"
fi

# Installed into ~/.swiftenv/versions
for path in "$VERSIONS_DIR"/*; do
  if [ -d "$path" ]; then
    print_version "${path##*/}" "swiftenv"
  fi
done

# Swift toolchains on OS X

check_toolchains() {
  TOOLCHAIN_DIR="$1"

  if [ -d "$TOOLCHAIN_DIR" ]; then
    for path in "$TOOLCHAIN_DIR"/*; do
      if [[ "$path" == *".xctoolchain" ]] && [ -d "$path" ]; then
        version="$(basename ${path##*/} .xctoolchain)"
        if [ "$version" != "swift-latest" ]; then
          print_version "${version%-RELEASE}" "toolchain"
        fi
      fi
    done
  fi
}

check_toolchains "/Library/Developer/Toolchains"
check_toolchains "$HOME/Library/Developer/Toolchains"

# Xcode installs
if command -v "mdfind" >/dev/null 2>&1; then
  XCODES="$(mdfind "kMDItemCFBundleIdentifier == 'com.apple.dt.Xcode'" 2>/dev/null)"
  for xcode in $XCODES; do
    if [ -d "$xcode" ]; then
      version_line="$(env DEVELOPER_DIR="$xcode" xcrun swift --version | head -n1)"
      version="swift-$(echo "$version_line" | cut -d " " -f 4)"
      print_version "$version" "xcode $xcode"
    fi
  done
fi
